<?php
/**
 * Created by PhpStorm.
 * User: shutao
 * Date: 2019-01-03
 * Time: 17:39
 */

namespace wechat\help;

use ttcommon\base\Data;
use wechat\services\WeSystemVar;

class WeTextHelp
{
    /**
     * 替换掉模板中的变量
     * @param string $content 待格式化的内容字符串
     * @param array $varParams 待替换变量的内容
     * @param bool $isReplaceSystemVars 是否同时替换系统变量，默认 true
     * @return string
     */
    public static function replace($content, $varParams = [], $isReplaceSystemVars = true)
    {
        if ($varParams && $content) {
            $replaces = [];
            $tplVars = [];
            preg_match_all('#<span class="wechat_var_tpl_(\w+)">[^<]+</span>#', $content, $tplVars);
            if ($tplVars) {
                foreach ($tplVars[1] as $key => $name) {
                    $replaces[] = [$tplVars[0][$key], isset($varParams[$name]) ? $varParams[$name] : ''];
                }
            }

            if ($replaces) {
                foreach ($replaces as $r) {
                    $content = str_replace($r[0], $r[1], $content);
                }
            }
        }
        return $isReplaceSystemVars && $content ? self::replaceSystemVar($content) : $content;
    }

    /**
     * 替换内容中的系统变量
     * @param string $content
     * @return string
     */
    public static function replaceSystemVar($content)
    {
        if ($content) {
            // 提取出系统变量
            $replaces = [];
            preg_match_all('#<span class="wechat_var_system_(\w+)">[^<]+</span>#', $content, $systemVars);
            if ($systemVars) {

                foreach ($systemVars[1] as $key => $name) {
                    $info = WeSystemVar::vars($name);
                    $replaces[] = [
                        $systemVars[0][$key],
                        // 优先使用 value
                        isset($info['value']) ? $info['value'] : Data::hasValue($info, 1, '')
                    ];
                }
            }
            foreach ($replaces as $r) {
                $content = str_replace($r[0], $r[1], $content);
            }
        }
        return $content;
    }

    /**
     * 返回内容中的变量，稍后你可以使用 array_combine ( array $keys , array $values ) 来拼接替换的内容
     * @param string $content
     * @return array
     */
    public static function debugTplVars($content)
    {
        preg_match_all('#<span class="wechat_var_tpl_(\w+)">[^<]+</span>#', $content, $tplVars);
        return isset($tplVars[1]) ? $tplVars[1] : [];
    }

    /**
     * 查询内容中的系统变量，稍后你可以使用 array_combine ( array $keys , array $values ) 来拼接替换的内容，默认使用系统内置变量
     * @param $content
     * @return array
     */
    public static function debugSystemVars($content)
    {
        preg_match_all('#<span class="wechat_var_system_(\w+)">[^<]+</span>#', $content, $systemVars);
        return isset($systemVars[1]) ? $systemVars[1] : [];
    }
}